package com.bishe.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bishe.entity.OrderQuery;
import com.bishe.service.OrderService;
import com.bishe.entity.Order;
import com.bishe.mapper.OrderMapper;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
* @author wwz
* @description 针对表【order】的数据库操作Service实现
* @createDate 2024-03-15 12:05:03
*/
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order>
    implements OrderService {

    @Override
    public IPage<?> getPage(Page<Order> page, Order order) {
        Date endTime = order.getEndTime();
        Date startTime = order.getStartTime();
        LambdaQueryWrapper<Order> wrapper = new LambdaQueryWrapper<>();

        if (StrUtil.isNotEmpty(order.getOrderNo())){
            wrapper = Wrappers.lambdaQuery(Order.class).like(Order::getOrderNo, order.getOrderNo());
        }

        if (ObjectUtil.isNotEmpty(startTime) && ObjectUtil.isNotEmpty(endTime)){
            wrapper = Wrappers.lambdaQuery(Order.class).between(Order::getCreateTime, startTime, endTime);

        }

        return page(page, wrapper);
    }

    @Override
    public IPage<?> myOrders(OrderQuery query) {
        StpUtil.checkLogin();
        String loginIdAsString = StpUtil.getLoginIdAsString();

        Date endTime = query.getEndTime();
        Date startTime = query.getStartTime();

        if (query.getType()!=null && "user".equals(query.getType())){
            return page(query.toPage(), Wrappers.lambdaQuery(Order.class)
                    .eq(ObjectUtil.isNotEmpty(query.getStatus()), Order::getStatus, query.getStatus())
                    .between(ObjectUtil.isAllNotEmpty(query.getStartTime(),query.getEndTime()),Order::getCreateTime, startTime, endTime)
                    .orderByDesc(query.getIsPrice().equals(true), Order::getPrice)
            );
        }



        IPage<Order> page = page(query.toPage(), Wrappers.lambdaQuery(Order.class)
                .eq(Order::getUid, loginIdAsString)
                .eq(ObjectUtil.isNotEmpty(query.getStatus()), Order::getStatus, query.getStatus())
                .between(ObjectUtil.isAllNotEmpty(query.getStartTime(),query.getEndTime()),Order::getCreateTime, startTime, endTime)
                .orderByDesc(query.getIsPrice().equals(true), Order::getPrice)
        );

        return page;
    }

}




